package com.ja.openchat.ui.chat;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.graphics.Bitmap;
import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.dueeeke.videocontroller.component.PrepareView;
import com.dueeeke.videoplayer.player.VideoView;
import com.github.chrisbanes.photoview.OnPhotoTapListener;
import com.github.chrisbanes.photoview.PhotoView;
import com.gyf.immersionbar.ImmersionBar;
import com.ja.openchat.BR;
import com.ja.openchat.R;
import com.ja.openchat.ui.base.JaBaseActivity;
import com.ja.openchat.views.CustomStandardVideoController;
import com.ja.openchat.views.FingerViewGroup;
import com.ja.openchat.views.Utils;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.vachel.editor.PictureEditActivity;
import com.zy.openchat.App;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgEvent;
import com.zy.openchat.core.model.file.DocumentInfo;
import com.zy.openchat.core.model.file.FileInfo;
import com.zy.openchat.core.model.file.FileTaskInfo;
import com.zy.openchat.core.model.message.MessageInfo;
import com.zy.openchat.util.SingleMediaScanner;
import com.zy.openchat.util.glide.GlideApp;
import com.zy.openchat.util.share.GoShare;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import okio.BufferedSource;
import okio.Okio;
import okio.Sink;

/**
 * @author imndx
 */
public class PreviewMediaActivity extends JaBaseActivity {
    private SparseArray<View> views;
    private ViewPager viewPager;
    private MMPagerAdapter adapter;
    private static int currentPosition = -1;
    private static List<MessageInfo> entries;
    private boolean pendingPreviewInitialMedia;

    private class MMPagerAdapter extends PagerAdapter {
        private List<MessageInfo> entries;

        public MMPagerAdapter(List<MessageInfo> entries) {
            this.entries = entries;
        }

        @NonNull
        @Override
        public Object instantiateItem(@NonNull ViewGroup container, int position) {
            View view;
            MessageInfo entry = entries.get(position);
            if (isImageType(entry)) {
                view = LayoutInflater.from(PreviewMediaActivity.this).inflate(R.layout.preview_photo, null);
            } else {
                view = LayoutInflater.from(PreviewMediaActivity.this).inflate(R.layout.preview_video_new, null);
            }
            view.setTag(position);
            container.addView(view);
            views.put(position % 3, view);
            if (pendingPreviewInitialMedia) {
                preview(view, entry);
            }
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, @NonNull Object object) {
            // do nothing ?
            container.removeView((View) object);
        }

        @Override
        public int getCount() {
            return entries == null ? 0 : entries.size();
        }

        public MessageInfo getEntry(int position) {
            return entries.get(position);
        }

        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
            return view == object;
        }

        private View mCurrentView;
        @Override
        public void setPrimaryItem(ViewGroup container, int position, Object object) {
            mCurrentView = (View)object;
        }
        public View getPrimaryItem() {
            return mCurrentView;
        }
    }

    final ViewPager.OnPageChangeListener pageChangeListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            // TODO 可以在此控制透明度
        }

        @Override
        public void onPageSelected(int position) {
            View view = views.get(position % 3);
            if (view == null) {
                // pending layout
                return;
            }
            releaseVideoView();
            setCurrentTitle(position);
            MessageInfo entry = adapter.getEntry(position);
            preview(view, entry);
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    };

    private void releaseVideoView() {
        Utils.removeViewFormParent(mVideoView);
        mVideoView.release();
        if (mVideoView.isFullScreen()) {
            mVideoView.stopFullScreen();
        }
//        mController.removeAllControlComponent();
    }

    private boolean isImageType(MessageInfo message){
        if(message==null){
            return false;
        }
        if(message.messageType == TelegramManager.MessageType.MessageType_Photo){
            return true;
        }
        if(message.messageType == TelegramManager.MessageType.MessageType_Document){
            if(message.content!=null&&message.content.document!=null){
                DocumentInfo documentInfo = message.content.document;
                return DocumentInfo.isImageFile(documentInfo.file_name);
            }
        }
        if(message.messageType == TelegramManager.MessageType.MessageType_Animation){
            if(message.content!=null&&message.content.animation!=null){
                String filePath = message.content.animation.localAnimationPath();
                if(!TextUtils.isEmpty(filePath)&&DocumentInfo.isGifeFile(filePath)){
                    return true;
                }
            }

        }
        return false;
    }

    private void preview(View view, MessageInfo message) {
        preview(view, message,false);
    }

    private void preview(View view, MessageInfo message,boolean isNotify) {
        if (isImageType(message)) {
            iv_bar_right.setVisibility(View.VISIBLE);
            previewImage(view, message);
        } else {
            if(message.messageType == TelegramManager.MessageType.MessageType_Animation){
                iv_bar_right.setVisibility(View.GONE);
            }else{
                iv_bar_right.setVisibility(View.VISIBLE);
            }
            previewVideo(view, message,isNotify);
        }
    }



    private void previewVideo(View view, MessageInfo entry,boolean isNotify) {
        if(!isNotify){
            releaseVideoView();
        }

        PrepareView mPrepareView = view.findViewById(R.id.prepare_view);
        ImageView photoView = mPrepareView.findViewById(R.id.thumb);
        mPrepareView.setClickable(false);
        photoView.setScaleType(ImageView.ScaleType.FIT_CENTER);
        if(entry.messageType == TelegramManager.MessageType.MessageType_Video){
            if (entry.content.video.thumbnail!=null&&entry.content.video.thumbnail.isThumbnailDownloaded()) {
                GlideApp.with(photoView).load(entry.content.video.thumbnail.file.local.path).into(photoView);
            }
            if (entry.isVideoFileDownloaded()) {
                GlideApp.with(photoView).load(entry.getVideoFile().local.path).into(photoView);
            }
            if(!isNotify&&!entry.getVideo().isVideoDownloadComplete()){
                TelegramManager.getTelegramManager().downloadFile(entry.chat_id+"_" + entry.id, entry.getVideoFileId(), entry.getVideoFile().downloadedStart(), TelegramManager.FileType.FileType_Message_Video);
            }
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (entry.isVideoFileDownloaded()) {
                        playVideo(v, entry.getVideoFile().local.path);
                    }
                }
            });
        }else if(entry.messageType == TelegramManager.MessageType.MessageType_Animation){
            if (entry.isAnimationDownloaded()) {
                GlideApp.with(photoView).load(entry.getAnimationFile().local.path).into(photoView);
            }else{
                TelegramManager.getTelegramManager().downloadFile(entry.chat_id+"_" + entry.id, entry.getAnimationFileId(), 0, TelegramManager.FileType.FileType_Message_Animation);
            }
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (entry.isAnimationDownloaded()) {
                        playVideo(view, entry.getAnimationFile().local.path);
                    }
                }
            });
        }else{
            DocumentInfo documentInfo = entry.content.document;
            if(documentInfo!=null){
                if (documentInfo.isFileDownloaded()) {
                    GlideApp.with(photoView).load(documentInfo.localFilePath()).into(photoView);
                }else{
                    TelegramManager.getTelegramManager().downloadFile(entry.chat_id+"_" + entry.id, documentInfo.document.id, 0, TelegramManager.FileType.FileType_Message_Document);
                }
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (documentInfo.isFileDownloaded()) {
                            playVideo(view, documentInfo.localFilePath());
                        }
                    }
                });
            }
        }

        if(isFirstShow){
            isFirstShow = false;
            view.post(new Runnable() {
                @Override
                public void run() {
                    if(view!=null){
                        view.performClick();
                    }
                }
            });
        }

    }

    private boolean isFirstShow = true;

    private void playVideo(View view, String videoUrl) {
        FrameLayout mPlayerContainer = view.findViewById(R.id.player_container);
        PrepareView mPrepareView = view.findViewById(R.id.prepare_view);
        mVideoView.setUrl(videoUrl);
        mController.addControlComponent(mPrepareView, true);
        Utils.removeViewFormParent(mVideoView);
        mPlayerContainer.addView(mVideoView, 0);
        long position = -1;
        if(mVideoView.isPlaying()){
            position = mVideoView.getCurrentPosition();
        }
        mVideoView.start(); //开始播放，不调用则不自动播放
        if(position>0){
            mVideoView.seekTo(position);
        }
    }
    private CustomStandardVideoController mController;
    protected VideoView mVideoView;
    protected void initVideoView() {
        mVideoView = new VideoView(this);
        mVideoView.setOnStateChangeListener(new VideoView.SimpleOnStateChangeListener() {
            @Override
            public void onPlayStateChanged(int playState) {
                //监听VideoViewManager释放，重置状态
                if (playState == VideoView.STATE_IDLE) {
                }
            }
        });
        mController = new CustomStandardVideoController(this);
        mController.addDefaultControlComponent("预览");
        mVideoView.setVideoController(mController); //设置控制器
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTgEvent(final TgEvent tg_event){
        if((tg_event.event == TelegramManager.EUser_TgEvent.EUser_Td_Message_Preview_Photo_Ok
                ||tg_event.event == TelegramManager.EUser_TgEvent.EUser_Td_Message_Video_Ok
                ||tg_event.event == TelegramManager.EUser_TgEvent.EUser_Td_Message_Animation_Ok
                ||tg_event.event == TelegramManager.EUser_TgEvent.EUser_Td_Message_Document_Ok)&&tg_event.data instanceof FileTaskInfo &&tg_event.dataEx instanceof FileInfo){
            FileInfo fileInfo = (FileInfo) tg_event.dataEx;
            String ids = ((FileTaskInfo)tg_event.data).id;
            if(!TextUtils.isEmpty(ids)&&ids.contains("_")) {
                String[] idArray = ids.split("_");
                if (idArray.length >= 2) {
                    if (idArray[0].equals(String.valueOf(adapter.getEntry(0).chat_id))) {
                        for (int i = 0; i < adapter.getCount(); i++) {
                            MessageInfo message = adapter.getEntry(i);
                            if (message.id == Long.parseLong(idArray[1])) {
                                if(tg_event.event == TelegramManager.EUser_TgEvent.EUser_Td_Message_Preview_Photo_Ok){
                                    message.updatePreviewPhotoFile(fileInfo);
                                }else if(tg_event.event == TelegramManager.EUser_TgEvent.EUser_Td_Message_Document_Ok){
                                    message.updateDocumentFile(fileInfo);
                                }else if(tg_event.event == TelegramManager.EUser_TgEvent.EUser_Td_Message_Animation_Ok){
                                    message.updateAnimationFile(fileInfo);
                                }else{
                                    message.updateVideoFile(fileInfo);
                                }
                                View view = viewPager.findViewWithTag(i);
                                if(view!=null){
                                    if(tg_event.event == TelegramManager.EUser_TgEvent.EUser_Td_Message_Video_Ok&&message.getAnimationFile()!=null&&message.getAnimationFile().local!=null){
                                        playVideo(view,message.getAnimationFile().local.path);
                                    }else{
                                        preview(view,message,true);
                                    }
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    @Override
    protected boolean isHaveEventBus() {
        return true;
    }

    private void previewImage(View view, MessageInfo entry) {
        PhotoView photoView = view.findViewById(R.id.photoView);
        if(photoView==null){
            return;
        }
        photoView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                iv_bar_right.performClick();
                return false;
            }
        });
        if(entry.messageType == TelegramManager.MessageType.MessageType_Photo ){
            if(entry.isPreviewPhotoFileDownloaded()){
                GlideApp.with(PreviewMediaActivity.this).load(entry.getPreviewPhotoFile().local.path)
                        .into(photoView);
            }else{
                TelegramManager.getTelegramManager().downloadFile(entry.chat_id+"_" + entry.id, entry.getPreviewPhotoFileId(), 0, TelegramManager.FileType.FileType_Message_Preview_Photo);
                if (entry.isMessagePhotoDownloaded()) {
                    GlideApp.with(PreviewMediaActivity.this).load(entry.getMessagePhotoFile().local.path)
                            .into(photoView);
                }
            }
        }if(entry.messageType == TelegramManager.MessageType.MessageType_Animation){
            if (entry.isAnimationDownloaded()) {
                GlideApp.with(photoView).load(entry.getAnimationFile().local.path).into(photoView);
            }else{
                TelegramManager.getTelegramManager().downloadFile(entry.chat_id+"_" + entry.id, entry.getAnimationFileId(), 0, TelegramManager.FileType.FileType_Message_Animation);
            }
        }else if(entry.messageType == TelegramManager.MessageType.MessageType_Document){
            if(entry.isDocumentFileDownloaded()){
                GlideApp.with(PreviewMediaActivity.this).load(entry.content.document.localFilePath())
                        .into(photoView);
            }else{
                TelegramManager.getTelegramManager().downloadFile(entry.chat_id+"_" + entry.id, entry.content.document.document.id, 0, TelegramManager.FileType.FileType_Message_Document);
            }
        }
        photoView.setOnPhotoTapListener(new OnPhotoTapListener() {
            @Override
            public void onPhotoTap(ImageView view, float x, float y) {
                finish();
            }
        });
    }

    private TextView tv_bar_title;
    private AppCompatImageView iv_bar_right;

    @Override
    public void initView() {
        super.initView();
        views = new SparseArray<>(3);
        viewPager = findViewById(R.id.viewPager);
        adapter = new MMPagerAdapter(entries);
        viewPager.setAdapter(adapter);
        viewPager.setOffscreenPageLimit(1);
        viewPager.addOnPageChangeListener(pageChangeListener);
        tv_bar_title = findViewById(R.id.tv_bar_title);
        initVideoView();
        Toolbar toolbar = findViewById(R.id.toolbar);
        toolbar.setBackgroundResource(R.drawable.transparent_shape);
        ((ViewGroup.MarginLayoutParams)toolbar.getLayoutParams()).topMargin = ImmersionBar.getStatusBarHeight(this);
        tv_bar_title.setTextColor(ContextCompat.getColor(this,R.color.white));
        iv_bar_right = findViewById(R.id.iv_bar_right);
        iv_bar_right.setImageResource(R.mipmap.gengduo_preview);
        iv_bar_right.setVisibility(View.VISIBLE);
        iv_bar_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int currentIndex = viewPager.getCurrentItem();
                if(entries==null||entries.size()<=currentIndex){
                    return;
                }
                handleMedia(currentIndex);
            }
        });
        AppCompatImageView iv_bar_back = findViewById(R.id.iv_bar_back);
        iv_bar_back.setImageResource(R.mipmap.com_nav_ic_back_white_normal);
        iv_bar_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        try {
            if(!isImageType(entries.get(currentPosition))){
                isFirstShow = true;
            }else{
                isFirstShow = false;
            }
        }catch (Exception e){

        }
        if (currentPosition == 0) {
            viewPager.post(() -> {
                pageChangeListener.onPageSelected(0);
            });
            setCurrentTitle(0);
        } else {
            viewPager.setCurrentItem(currentPosition);
            pendingPreviewInitialMedia = true;
            setCurrentTitle(currentPosition);
        }
        if(entries!=null&&entries.size()>currentPosition&&entries.get(currentPosition).messageType == TelegramManager.MessageType.MessageType_Animation){
            iv_bar_right.setVisibility(View.GONE);
        }else{
            iv_bar_right.setVisibility(View.VISIBLE);
        }

        FingerViewGroup adFingerViewGroup = findViewById(R.id.ad_finger_vg);
        adFingerViewGroup.setOnAlphaChangeListener(new FingerViewGroup.onAlphaChangedListener() {
            @Override
            public void onAlphaChanged(float alpha) {
                Log.e("fengan","[onAlphaChanged]:alpha="+alpha);
            }

            @Override
            public void onTranslationYChanged(float translationY) {
                Log.e("fengan","[onTranslationYChanged]:translationY="+translationY);
            }

            @Override
            public void onFinishAction() {
                finish();
                overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
            }
        });


    }

    private void handleMedia(int currentIndex){
        String[] popuTitles;
        OnHandleMediaListener[] handles;
        MessageInfo messageInfo = entries.get(currentIndex);
        if(isImageType(messageInfo)){
            String qrcodeText = null;
            String filePath = getFilePathByMessage(messageInfo);
            if(!TextUtils.isEmpty(filePath)){
                if(TelegramManager.getTelegramManager().haveQrCodeByFilePath(filePath)){
                    qrcodeText = TelegramManager.getTelegramManager().getQrCodeByFilePath(filePath);
                }else{
                    View view = adapter.getPrimaryItem();
                    if(view!=null){
                        view.setDrawingCacheEnabled(true);
                        Bitmap bitmap = view.getDrawingCache();
                        if(bitmap!=null){
                            qrcodeText = TelegramManager.getTelegramManager().putQrCodeByFilePath(filePath,bitmap);
                        }
                        view.setDrawingCacheEnabled(false);
                    }
                }
            }
            if(TextUtils.isEmpty(qrcodeText)){
                popuTitles = new String[]{getString(R.string.save_album), getString(R.string.share_text),getString(R.string.edit_text)};
                handles = new OnHandleMediaListener[]{saveAlbumListener,shareMediaListener,editImageListener};
            }else{
                popuTitles = new String[]{getString(R.string.save_album), getString(R.string.share_text),getString(R.string.edit_text),getString(R.string.identify_qr_code)};
                final String qrcodeTextFinal = qrcodeText;
                handles = new OnHandleMediaListener[]{saveAlbumListener,shareMediaListener,editImageListener,new OnHandleMediaListener() {
                    @Override
                    public void invoke(MessageInfo messageInfo) {
                        Uri content_url = Uri.parse(qrcodeTextFinal);
                        Intent intent = new Intent(Intent.ACTION_VIEW, content_url);
                        startActivity(intent);
                    }
                }};
            }
            innerHandleMedia(popuTitles,handles);
        }else{
            popuTitles = new String[]{getString(R.string.save_album), getString(R.string.share_text)};
            handles = new OnHandleMediaListener[]{saveAlbumListener,shareMediaListener};
            innerHandleMedia(popuTitles,handles);
        }

    }

    private void innerHandleMedia(String[] popuTitles,OnHandleMediaListener[] handles){
        new XPopup.Builder(PreviewMediaActivity.this).asBottomList(null, popuTitles, new OnSelectListener() {
            @Override
            public void onSelect(int position, String text) {
                int currentIndex = viewPager.getCurrentItem();
                if(entries!=null&&entries.size()>currentIndex){
                    MessageInfo messageInfo = entries.get(currentIndex);
                    if(handles!=null&&handles.length>position){
                        handles[position].invoke(messageInfo);
                    }
                }

            }
        }).show();
    }

    private OnHandleMediaListener editImageListener = new OnHandleMediaListener() {
        @Override
        public void invoke(MessageInfo messageInfo) {
            String filePath = getFilePathByMessage(messageInfo);
            if(TextUtils.isEmpty(filePath)){
                ToastUtils.showShort(getString(R.string.downloading_try_again));
                return;
            }
            Intent intent = new Intent();
            intent.putExtra(PictureEditActivity.EXTRA_IMAGE_URI, Uri.fromFile(new File(filePath)));
            intent.putExtra(PictureEditActivity.EXTRA_TYPE,1);
            intent.setClass(PreviewMediaActivity.this,GoChatPicEditActivity.class);
            PreviewMediaActivity.this.startActivity(intent);
        }
    };

    private OnHandleMediaListener shareMediaListener = new OnHandleMediaListener() {
        @Override
        public void invoke(MessageInfo messageInfo) {
            String filePath = getFilePathByMessage(messageInfo);
            if(TextUtils.isEmpty(filePath)){
                ToastUtils.showShort(getString(R.string.downloading_try_again));
                return;
            }
            new GoShare.FShareBuilder(PreviewMediaActivity.this, App.getInstanse().getPackageName() + ".utilcode.fileprovider")
                    .setFilePath(filePath)
                    .setShareSubject(getResources().getString(R.string.app_name))
                    .build()
                    .shareByCustom();

        }
    };

    private OnHandleMediaListener saveAlbumListener = new OnHandleMediaListener() {
        @Override
        public void invoke(MessageInfo messageInfo) {
            String filePath = getFilePathByMessage(messageInfo);
            if(TextUtils.isEmpty(filePath)){
                ToastUtils.showShort(getString(R.string.downloading_try_again));
                return;
            }
            if(isImageType(messageInfo)){
                try {
                    MediaStore.Images.Media.insertImage(getContentResolver(), filePath, getResources().getString(R.string.app_name), getResources().getString(R.string.app_name));
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                new SingleMediaScanner(getApplicationContext(), filePath, new SingleMediaScanner.ScanListener() {
                    @Override
                    public void onScanFinish() {
                        ToastUtils.showShort(getString(R.string.save_album_success));
                    }
                });

            }else{
                try {
                    saveVideo(PreviewMediaActivity.this,new File(filePath));
                }catch (Exception e){
                    e.printStackTrace();
                }

            }
        }
    };

    private String getFilePathByMessage(MessageInfo messageInfo){
        String filePath = null;
        if(isImageType(messageInfo)){
            if(messageInfo.messageType == TelegramManager.MessageType.MessageType_Photo){
                if(messageInfo.isPreviewPhotoFileDownloaded()){
                    filePath = messageInfo.getPreviewPhotoFile().local.path;
                }else if(messageInfo.isMessagePhotoFileDownloaded()){
                    filePath = messageInfo.getMessagePhotoFile().local.path;
                }

            }else if(messageInfo.messageType == TelegramManager.MessageType.MessageType_Document){
                filePath = messageInfo.content.document.localFilePath();
            }
        }else{
            if(messageInfo.messageType == TelegramManager.MessageType.MessageType_Video){
                if(messageInfo.isVideoFileDownloaded()){
                    filePath = messageInfo.getVideoFile().local.path;
                }
            }else if(messageInfo.messageType == TelegramManager.MessageType.MessageType_Animation){
                if(messageInfo.isAnimationDownloaded()){
                    filePath = messageInfo.getAnimationFile().local.path;
                }
            }else if(messageInfo.messageType == TelegramManager.MessageType.MessageType_Document){
                filePath = messageInfo.content.document.localFilePath();
            }

        }
        return filePath;
    }

    private static final String VIDEO_BASE_URI = "content://media/external/video/media";

    private void insertVideo(String videoPath, Context context) {
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        retriever.setDataSource(videoPath);
        int nVideoWidth = Integer.parseInt(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH));
        int nVideoHeight = Integer.parseInt(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT));
        int duration = Integer
                .parseInt(retriever
                        .extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
        long dateTaken = System.currentTimeMillis();
        File file = new File(videoPath);
        String title = file.getName();
        String filename = file.getName();
        String mime = "video/mp4";
        ContentValues mCurrentVideoValues = new ContentValues(9);
        mCurrentVideoValues.put(MediaStore.Video.Media.TITLE, title);
        mCurrentVideoValues.put(MediaStore.Video.Media.DISPLAY_NAME, filename);
        mCurrentVideoValues.put(MediaStore.Video.Media.DATE_TAKEN, dateTaken);
        mCurrentVideoValues.put(MediaStore.MediaColumns.DATE_MODIFIED, dateTaken / 1000);
        mCurrentVideoValues.put(MediaStore.Video.Media.MIME_TYPE, mime);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
//            String newPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES) + File.separator +paramFile.getName();
//            try {
//                fileCopy(paramFile.getAbsolutePath(),newPath);
//            }catch (Exception e){
//                e.printStackTrace();
//            }
            mCurrentVideoValues.put(MediaStore.Video.Media.RELATIVE_PATH, videoPath);
        }else{
            mCurrentVideoValues.put(MediaStore.Video.Media.DATA, videoPath);
        }
//        mCurrentVideoValues.put(MediaStore.Video.Media.DATA, videoPath);
        mCurrentVideoValues.put(MediaStore.Video.Media.WIDTH, nVideoWidth);
        mCurrentVideoValues.put(MediaStore.Video.Media.HEIGHT, nVideoHeight);
        mCurrentVideoValues.put(MediaStore.Video.Media.RESOLUTION, Integer.toString(nVideoWidth) + "x" + Integer.toString(nVideoHeight));
        mCurrentVideoValues.put(MediaStore.Video.Media.SIZE, new File(videoPath).length());
        mCurrentVideoValues.put(MediaStore.Video.Media.DURATION, duration);
        ContentResolver contentResolver = context.getContentResolver();
        Uri videoTable = Uri.parse(VIDEO_BASE_URI);
        Uri uri = contentResolver.insert(videoTable, mCurrentVideoValues);
        writeFile(videoPath, mCurrentVideoValues, contentResolver, uri);
    }

    private void writeFile(String imagePath, ContentValues values, ContentResolver contentResolver, Uri item) {
        try (OutputStream rw = contentResolver.openOutputStream(item, "rw")) {
            // Write data into the pending image.
            Sink sink = Okio.sink(rw);
            BufferedSource buffer = Okio.buffer(Okio.source(new File(imagePath)));
            buffer.readAll(sink);
            values.put(MediaStore.Video.Media.IS_PENDING, 0);
            contentResolver.update(item, values, null, null);
            new File(imagePath).delete();
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                Cursor query = getContentResolver().query(item, null, null, null);
                if (query != null) {
                    int count = query.getCount();
                    Log.e("writeFile","writeFile result :" + count);
                    query.close();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 保存视频
     * @param context
     * @param file
     */
    public static void saveVideo(Context context, File file) {
        //是否添加到相册
        ContentResolver localContentResolver = context.getContentResolver();
        long paramLong =  System.currentTimeMillis();
        ContentValues localContentValues = new ContentValues();
        localContentValues.put("title", file.getName());
        localContentValues.put("_display_name", file.getName());
        localContentValues.put("mime_type", "video/mp4");
        localContentValues.put("datetaken", Long.valueOf(paramLong));
        localContentValues.put("date_modified", Long.valueOf(paramLong));
        localContentValues.put("date_added", Long.valueOf(paramLong));
        String newPath;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            newPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + File.separator +file.getName();
            try {
                fileCopy(file.getAbsolutePath(),newPath);
            }catch (Exception e){
                e.printStackTrace();
            }
            localContentValues.put(MediaStore.Video.Media.RELATIVE_PATH, Environment.DIRECTORY_MOVIES+ File.separator +file.getName());
        }else{
            newPath = file.getAbsolutePath();
            localContentValues.put("_data", file.getAbsolutePath());
        }

        localContentValues.put("_size", Long.valueOf(file.length()));
        Uri localUri = localContentResolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, localContentValues);
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, localUri));

        new SingleMediaScanner(context.getApplicationContext(), newPath, new SingleMediaScanner.ScanListener() {
            @Override
            public void onScanFinish() {
                ToastUtils.showShort(context.getString(R.string.save_album_success));
            }
        });
    }

    public static boolean fileCopy(String oldFilePath,String newFilePath) throws IOException {
        //如果原文件不存在
        if(fileExists(oldFilePath) == false){
            return false;
        }
//        if(fileExists(newFilePath)==false){
//            new File(newFilePath).createNewFile();
//        }
        //获得原文件流
        FileInputStream inputStream = new FileInputStream(new File(oldFilePath));
        byte[] data = new byte[1024];
        //输出流
        FileOutputStream outputStream =new FileOutputStream(new File(newFilePath));
        //开始处理流
        while (inputStream.read(data) != -1) {
            outputStream.write(data);
        }
        inputStream.close();
        outputStream.close();
        return true;
    }

    public static boolean fileExists(String filePath) {
        File file = new File(filePath);
        return file.exists();
    }


    private void setCurrentTitle(int currentIndex){
        if(entries!=null&&entries.size()>currentIndex){
            tv_bar_title.setText(String.format("%d/%d",currentIndex+1,entries.size()));
        }else{
            tv_bar_title.setText("");
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(mVideoView!=null){
            mVideoView.pause();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(mVideoView!=null){
            mVideoView.resume();
        }

    }

//    @Override
//    public void onBackPressed() {
//        if(currentVideoView!=null&&currentVideoView.findViewById(R.id.videoView)!=null){
//            if (!((VideoView)currentVideoView.findViewById(R.id.videoView)).onBackPressed()) {
//                super.onBackPressed();
//            }
//        }
//    }


    @Override
    protected boolean isHaveButterKnife() {
        return true;
    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_mm_preview;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        entries = null;
        if(mVideoView!=null){
            mVideoView.release();
        }
    }

    public static void previewMedia(Context context, List<MessageInfo> entries, int current) {
        if (entries == null || entries.isEmpty()) {
            Log.w(PreviewMediaActivity.class.getSimpleName(), "message is null or empty");
            return;
        }
        PreviewMediaActivity.entries = entries;
        PreviewMediaActivity.currentPosition = current;
        Intent intent = new Intent(context, PreviewMediaActivity.class);
        context.startActivity(intent);
    }

    public static void previewImage(Context context, MessageInfo imageMessageContent) {
        List<MessageInfo> entries = new ArrayList<>();
        entries.add(imageMessageContent);
        previewMedia(context, entries, 0);
    }


    public static void previewVideo(Context context, MessageInfo videoMessageContent) {
        List<MessageInfo> entries = new ArrayList<>();

        entries.add(videoMessageContent);
        previewMedia(context, entries, 0);
    }


    @Override
    public void setStatusBar() {
        BarUtils.setStatusBarLightMode(this, false);
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT);
    }

}
